/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package weeek11.topic10;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 实现全局 ID 生成
 * @author lfy
 */
public class RedisSequence {
    public static void main(String[] args) {
        RedisSequence  redisSequence = new RedisSequence("127.0.0.1", 6379);
        String seqKey = "test_seq";
        Long id ;
        id = redisSequence.nextVal(seqKey);
        System.out.println("获取下一个id:"+id);
        id = redisSequence.currVal(seqKey);
        System.out.println("获取当前id:"+id);
        id = redisSequence.nextVal(seqKey);
        System.out.println("获取下一个id:"+id);
        id = redisSequence.currVal(seqKey);
        System.out.println("获取当前id:"+id);
        id = redisSequence.nextVal(seqKey);
        System.out.println("获取下一个id:"+id);
    }


    private final JedisPool jedisPool;

    public RedisSequence(String host, int port) {
        jedisPool = new JedisPool(host, port);
    }

    public long nextVal (String key){
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.incrBy(key,1);
        }
    }
    public Long currVal(String key){
        try (Jedis jedis = jedisPool.getResource()) {
            String s = jedis.get(key);
            if (s == null || s.length() == 0) {
                return null;
            }
            return Long.valueOf(s);
        }
    }
}
